package com.fary.rabbitmq.routing;

import com.fary.rabbitmq.config.RabbitMQFactory;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author chenyq
 * @date 2023/11/28
 */

public class Consumer2 {

    //几个常量
    private static final String DIRECT_EXCHANGE = "directExchange";
    private static final String DIRECT_QUEUE_1 = "directQueue1";
    private static final String DIRECT_QUEUE_2 = "directQueue_2";

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = RabbitMQFactory.getConnectionFactory();

        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT, true, false, null);
            // 声明队列
            channel.queueDeclare(DIRECT_QUEUE_1, true, false, false, null);
            channel.queueDeclare(DIRECT_QUEUE_2, true, false, false, null);

            //队列绑定交换机
            channel.queueBind(DIRECT_QUEUE_1, DIRECT_EXCHANGE, "error");
            channel.queueBind(DIRECT_QUEUE_2, DIRECT_EXCHANGE, "info");
            channel.queueBind(DIRECT_QUEUE_2, DIRECT_EXCHANGE, "error");
            channel.queueBind(DIRECT_QUEUE_2, DIRECT_EXCHANGE, "warning");

            Consumer consumer = new DefaultConsumer(channel) {
                //消费者收到后，做什么
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    //具体的业务逻辑
//                    System.out.println("consumerTag = " + consumerTag);
//                    System.out.println("envelope.getDeliveryTag() = " + envelope.getDeliveryTag());
//                    System.out.println("envelope.getExchange() = " + envelope.getExchange());
//                    System.out.println("envelope.getRoutingKey() = " + envelope.getRoutingKey());

                    System.out.println("body = " + new String(body));
                }
            };
            // 消费者消费消息
            channel.basicConsume(DIRECT_QUEUE_2, true, consumer);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }


}
